package com.yike.user.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkl.laop.sdk.exception.SDKException;
import com.yike.common.Response.LklApplyLedgerMerResponse;
import com.yike.common.Response.LklApplyLedgerReceiverResponse;
import com.yike.common.Response.LklFileResponse;
import com.yike.common.api.ApiResult;
import com.yike.common.entity.LklArea;
import com.yike.common.entity.ShopSplit;
import com.yike.common.entity.SysInfo;
import com.yike.common.exception.BusinessException;
import com.yike.common.pagination.PageInfo;
import com.yike.common.pagination.Paging;
import com.yike.common.request.ApplyForSepAccReq;
import com.yike.common.tool.LoginUtil;
import com.yike.common.tool.StringUtil;
import com.yike.common.vo.ShopSplitVo;
import com.yike.user.entity.*;
import com.yike.user.enums.ShopFileEnum;
import com.yike.user.lkl.api.V2SeparateAccounts;
import com.yike.user.lkl.incoming.IncomingApi;
import com.yike.user.lkl.incoming.LklIncomingProperties;
import com.yike.user.lkl.incoming.push.MerchantAudit;
import com.yike.user.lkl.incoming.push.MerchantModification;
import com.yike.user.lkl.incoming.request.*;
import com.yike.user.lkl.incoming.response.FileResponse;
import com.yike.user.lkl.incoming.response.MerchantResponse;
import com.yike.user.lkl.incoming.response.MerchantUpdateResponse;
import com.yike.user.mapper.*;
import com.yike.user.param.*;
import com.yike.user.service.PlatformShopService;
import com.yike.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 平台用户 服务实现类
 *
 * @author Sakura
 * @since 2024-10-29
 */
@Slf4j
@Service
public class PlatformShopServiceImpl implements PlatformShopService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopUserMapper shopUserMapper;
    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private AgentShopMapper agentShopMapper;
    @Autowired
    private ShopFileMapper shopFileMapper;

    @Autowired
    private ShopDetailsMapper shopDetailsMapper;

    @Autowired
    private ShopExpandMapper shopExpandMapper;

    @Autowired
    private ShopExpandFeeMapper shopExpandFeeMapper;

    @Autowired
    private IncomingApi incomingApi;


    @Autowired
    private V2SeparateAccounts v2SeparateAccounts;
    @Resource
    private LklIncomingProperties properties;

    @Resource
    private ShopSplitMapper shopSplitMapper;
    @Resource
    private SysInfoMapper sysInfoMapper;

    @Resource
    private LklAreaMapper lklAreaMapper;

    @Resource
    private AgentAreaSettingMapper  agentAreaSettingMapper;
    @Override
    @Transactional
    public ApiResult<String>  saveShop(PlatformShopParam platformShopParam) throws Exception {

        platformShopParam.getShopDetailsParam().setBusiCode("WECHAT_PAY");

        String msg = paramCheck(platformShopParam);//判空
        if(StringUtil.isNotBlank(msg)){
            return ApiResult.fail(500,msg);
        }
        platformShopParam.getShopDetailsParam().setContactMobile(platformShopParam.getMobile());
        platformShopParam.getShopDetailsParam().setContactName(platformShopParam.getContact());

        // 先判断当前手机号是否存在账号
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getMobile, platformShopParam.getMobile()));
        if (user == null) {
            // 如果用户不存在则创建一个用户
            user = new User();
            BeanUtils.copyProperties(platformShopParam, user);
            user.setUserNo(StringUtil.random(32)); // 生成用户ID
            user.setNickname(platformShopParam.getContact());
            user.setSource(platformShopParam.getShopName());
            user.setCreateBy(LoginUtil.getUserId());
            userMapper.insert(user);
        }
        // 判断商家是否存在
        Merchant merchant = merchantMapper.selectOne(Wrappers.lambdaQuery(Merchant.class)
                .eq(Merchant::getUserId, user.getId()));
        if (merchant == null) {
            // 创建一条商户记录
            merchant = new Merchant();
            BeanUtils.copyProperties(platformShopParam, merchant);
            merchant.setMerchantNo("86" + StringUtil.getStrNo());
            merchant.setUserId(user.getId());
            merchant.setName(platformShopParam.getShopName());
            merchant.setCreateBy(LoginUtil.getUserId());
            merchantMapper.insert(merchant);
        }



        // 最后创建一个店铺信息
        Shop shop = new Shop();
        BeanUtils.copyProperties(platformShopParam, shop);
        shop.setMerchantId(merchant.getId());
        // 生产一个店铺编号
        shop.setShopNo("88" + StringUtil.getStrNo());
        shop.setCreateBy(LoginUtil.getUserId());
        shopMapper.insert(shop);

        // 创建店主
        ShopUser shopUser = new ShopUser();
        shopUser.setShopId(shop.getId());
        shopUser.setUserId(merchant.getUserId());
        shopUser.setType(1);
        shopUser.setCreateBy(LoginUtil.getUserId());
        shopUserMapper.insert(shopUser);

        // 处理代理商绑定逻辑
        if (StringUtil.isNotBlank(platformShopParam.getAgentNo())) {
            // 如果代理商信息不为空则直接绑定店铺到代理商
            Agent agent = agentMapper.selectOne(Wrappers.lambdaQuery(Agent.class)
                    .eq(Agent::getAgentNo, platformShopParam.getAgentNo()));
            if (agent == null) {
                throw new BusinessException("代理商信息异常");
            }
            AgentShop agentShop = new AgentShop();
            agentShop.setShopId(shop.getId());
            agentShop.setAgentId(agent.getId());
            agentShop.setCreateBy(LoginUtil.getUserId());
            agentShopMapper.insert(agentShop);
        }

        // 保存文件信息
        if (platformShopParam.getFiles() != null) {
            for (ShopFileParam shopFileParam:platformShopParam.getFiles()) {
                ShopFile shopFile = new ShopFile();
                BeanUtils.copyProperties(shopFileParam, shopFile);
                shopFile.setType(shopFileParam.getTypes());
                shopFile.setShopId(shop.getId());
                shopFileMapper.insert(shopFile);
            }
        }
        MerchantResponse merchantResponse =  this.merchantPost(platformShopParam);

        System.out.println(merchantResponse);
        //保存店铺详情信息
        ShopDetails shopDetails = new ShopDetails();
        BeanUtils.copyProperties(platformShopParam.getShopDetailsParam(), shopDetails);
        shopDetails.setShopId(String.valueOf(shop.getId()));
        shopDetails.setMerchantId(String.valueOf(merchant.getId()));
        shopDetails.setCreateBy(LoginUtil.getUserId());
        shopDetails.setCreateTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        shopDetails.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
//        shopDetails.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));
//
//        shopDetails.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
//        shopDetails.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));
//
//        shopDetails.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
//        shopDetails.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));


        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLarIdCardStart())){
            shopDetails.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
        }

        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLarIdCardEnd())){
            shopDetails.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));

        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLicenseDtStart())){
            shopDetails.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLicenseDtEnd())){
            shopDetails.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getAccountIdDtStart())){
            shopDetails.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getAccountIdDtEnd())) {
            shopDetails.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));
        }
        shopDetails.setMerAddr(platformShopParam.getAddress());

        if(ObjectUtils.isEmpty(merchantResponse)){
            shopDetails.setStatus("Incoming_fail");
            shopDetails.setCustomerNo("");

        }else {
            shopDetails.setStatus("WAIT_AUDI");
            shopDetails.setCustomerNo(merchantResponse.getMerchantNo());
        }
        shopDetailsMapper.insert(shopDetails);

        //保存业务拓展信息
        ShopExpand shopExpand = new ShopExpand();
        BeanUtils.copyProperties(platformShopParam.getShopDetailsParam().getShopExpandParam(), shopExpand);
        shopExpand.setShopId(shop.getId());
        shopExpand.setCreateBy(LoginUtil.getUserId());
        shopExpand.setUpdateBy(LoginUtil.getUserId());
        shopExpand.setCreateTime(new Date());
        shopExpandMapper.insert(shopExpand);

        //保存业务拓展费率信息
        List<ShopExpandFeeParam> shopExpandFeeParams = platformShopParam.getShopDetailsParam().getShopExpandParam().getShopExpandFeeParamList();
        for (ShopExpandFeeParam shopExpandFeeParam : shopExpandFeeParams){
            ShopExpandFee shopExpandFee = new ShopExpandFee();
            BeanUtils.copyProperties(shopExpandFeeParam, shopExpandFee);
            shopExpandFee.setShopDetailsId(shopDetails.getId());
            shopExpandFee.setCreateBy(LoginUtil.getUserId());
            shopExpandFee.setCreateTime(new Date());
            shopExpandFeeMapper.insert(shopExpandFee);
        }

        return ApiResult.ok("请求成功");

    }

    // 发起拉卡拉进件
    public MerchantResponse merchantPost(PlatformShopParam platformShopParam) throws Exception {
        MerchantRequest merchantRequest = new MerchantRequest();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BeanUtils.copyProperties(platformShopParam.getShopDetailsParam(), merchantRequest);

//        merchantRequest.setProvinceCode(platformShopParam.getProvCode() );
//        merchantRequest.setCityCode(platformShopParam.getCityCode() );
//        merchantRequest.setCountyCode(platformShopParam.getDistCode() );
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLarIdCardStart())){
            merchantRequest.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
        }

        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLarIdCardEnd())){
            merchantRequest.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));

        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLicenseDtStart())){
            merchantRequest.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getLicenseDtEnd())){
            merchantRequest.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getAccountIdDtStart())){
            merchantRequest.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
        }
        if(ObjectUtils.isNotEmpty(platformShopParam.getShopDetailsParam().getAccountIdDtEnd())) {
            merchantRequest.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));
        }

        merchantRequest.setProvinceCode( getLklAreaCode(platformShopParam.getProvCode()) );
        merchantRequest.setCityCode(getLklAreaCode(platformShopParam.getCityCode()) );
        merchantRequest.setCountyCode(getLklAreaCode(platformShopParam.getDistCode() ));

        merchantRequest.setMerAddr(platformShopParam.getAddress() );
        merchantRequest.setLatitude(String.valueOf(platformShopParam.getLatitude()));
        merchantRequest.setLongtude(String.valueOf(platformShopParam.getLongitude()));
        //业务拓展相关参数
        List<ShopExpandFeeParam> shopExpandFeeParams = platformShopParam.getShopDetailsParam().getShopExpandParam().getShopExpandFeeParamList();
        List<Fee> fees = new ArrayList<>();
        for (ShopExpandFeeParam shopExpandFeeParam : shopExpandFeeParams) {
            Fee  fee = new Fee();

            if(shopExpandFeeParam.getFeeCode().equals("UNIONPAY_WALLET_DEBIT_FEE") || shopExpandFeeParam.getFeeCode().equals("DEBIT_CARD")){
                BeanUtils.copyProperties(shopExpandFeeParam, fee);
            }else {
                fee.setFeeCode(shopExpandFeeParam.getFeeCode());
                fee.setFeeValue(shopExpandFeeParam.getFeeValue());
            }


            fees.add(fee);
        }

        ShopExpandParam shopExpandParams = platformShopParam.getShopDetailsParam().getShopExpandParam();
        BizContent bizContent = new BizContent();
        BeanUtils.copyProperties(shopExpandParams, bizContent);
        bizContent.setActivityId(properties.getActivityId());
        bizContent.setFees(fees);
        bizContent.setTermNum(String.valueOf(shopExpandParams.getTermNum()));
        merchantRequest.setBizContent(bizContent);

        Set<Attchments> list = new HashSet<>();
        //上传文件到拉卡拉
        if (platformShopParam.getFiles() != null) {
            for (ShopFileParam shopFileParam : platformShopParam.getFiles()) {
                if(ObjectUtils.isNotEmpty(shopFileParam) && StringUtil.isNotBlank(shopFileParam.getUrl())&& StringUtil.isNotBlank(shopFileParam.getName())){
                    String code = ShopFileEnum.getDescByCode(shopFileParam.getTypes());
                    if(StringUtil.isNotBlank(code)){
                        FileResponse fileResponse = incomingApi.IncomingFilesPost(new IncomingFiles(shopFileParam.getUrl(), code, "0", shopFileParam.getName()));
                        if(ObjectUtils.isNotEmpty(fileResponse) && StringUtil.isNotBlank(fileResponse.getUrl())){
                            Attchments attchments =  new Attchments(code, fileResponse.getUrl());
                            list.add(attchments);
                        }
                    }
                }



            }
        }
        merchantRequest.setAttchments(list);

        MerchantResponse merchantResponse = incomingApi.merchant(merchantRequest);
        return merchantResponse;


    }


    public String getLklAreaCode(String code) throws Exception {
        AreaInfoVo  areaInfoVo = agentAreaSettingMapper.getAgentArea(code);
        LklArea lklArea = lklAreaMapper.queryName(areaInfoVo.getName());
        return lklArea.getCode();
    }


    // 发起拉卡拉改件
    public MerchantUpdateResponse merchantUpdate(ShopDetails shopDetails) throws Exception {
        MerchantUpdateRequest merchantRequest = new MerchantUpdateRequest();

        BeanUtils.copyProperties(shopDetails, merchantRequest);
        //merchantRequest.setCustomerNo(platformShopParam.getShopDetailsParam().getOpenningBankCode());
        merchantRequest.setCustomerNo(Long.valueOf(shopDetails.getExternalCustomerNo()));
        MerchantUpdateResponse merchantResponse = incomingApi.merchantUpdate(merchantRequest);
        return merchantResponse;
    }


    public MerchantRequest setMerchantRequest(PlatformShopParam platformShopParam) throws Exception {
        MerchantRequest merchantRequest = new MerchantRequest();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BeanUtils.copyProperties(platformShopParam.getShopDetailsParam(), merchantRequest);

//        merchantRequest.setProvinceCode(platformShopParam.getProvCode() );
//        merchantRequest.setCityCode(platformShopParam.getCityCode() );
//        merchantRequest.setCountyCode(platformShopParam.getDistCode() );
        merchantRequest.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
        merchantRequest.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));

        merchantRequest.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
        merchantRequest.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));

        merchantRequest.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
        merchantRequest.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));

        merchantRequest.setProvinceCode( getLklAreaCode(platformShopParam.getProvCode()) );
        merchantRequest.setCityCode(getLklAreaCode(platformShopParam.getCityCode()) );
        merchantRequest.setCountyCode(getLklAreaCode(platformShopParam.getDistCode() ));

        merchantRequest.setMerAddr(platformShopParam.getAddress() );
        merchantRequest.setLatitude(String.valueOf(platformShopParam.getLatitude()));
        merchantRequest.setLongtude(String.valueOf(platformShopParam.getLongitude()));
        //业务拓展相关参数
        List<ShopExpandFeeParam> shopExpandFeeParams = platformShopParam.getShopDetailsParam().getShopExpandParam().getShopExpandFeeParamList();
        List<Fee> fees = new ArrayList<>();
        for (ShopExpandFeeParam shopExpandFeeParam : shopExpandFeeParams) {
            Fee  fee = new Fee();

            if(shopExpandFeeParam.getFeeCode().equals("UNIONPAY_WALLET_DEBIT_FEE") || shopExpandFeeParam.getFeeCode().equals("DEBIT_CARD")){
                BeanUtils.copyProperties(shopExpandFeeParam, fee);
            }else {
                fee.setFeeCode(shopExpandFeeParam.getFeeCode());
                fee.setFeeValue(shopExpandFeeParam.getFeeValue());
            }


            fees.add(fee);
        }

        ShopExpandParam shopExpandParams = platformShopParam.getShopDetailsParam().getShopExpandParam();
        BizContent bizContent = new BizContent();
        BeanUtils.copyProperties(shopExpandParams, bizContent);
        bizContent.setActivityId(properties.getActivityId());
        bizContent.setFees(fees);
        bizContent.setTermNum(String.valueOf(shopExpandParams.getTermNum()));
        merchantRequest.setBizContent(bizContent);
        return merchantRequest;
    }


    public MerchantUpdateResponse merchantSettleUpdate(PlatformShopParam platformShopParam,String customerNo) throws Exception {
        MerchantRequest merchantRequest = setMerchantRequest(platformShopParam);
        MerchantUpdateResponse merchantResponse = incomingApi.merchantSettleUpdate(merchantRequest,customerNo);
        return merchantResponse;
    }

    public MerchantUpdateResponse merchantFeeUpdate(PlatformShopParam platformShopParam,String customerNo) throws Exception {
        MerchantRequest merchantRequest = setMerchantRequest(platformShopParam);
        MerchantUpdateResponse merchantResponse = incomingApi.merchantFeeUpdate(merchantRequest,customerNo);
        return merchantResponse;
    }


    @Override
    @Transactional
    public ApiResult<String> updateShop(PlatformShopParam platformShopParam) throws Exception {
        paramCheck(platformShopParam);//判空

        String msg = paramCheck(platformShopParam);//判空
        if(StringUtil.isNotBlank(msg)){
            return ApiResult.fail(500,msg);
        }
        platformShopParam.getShopDetailsParam().setContactMobile(platformShopParam.getMobile());
        platformShopParam.getShopDetailsParam().setContactName(platformShopParam.getContact());

        // 先获取店铺信息
        Shop shop = shopMapper.selectById(platformShopParam.getId());
        if (shop == null) {
            throw new BusinessException("店铺信息异常");
        }
        ShopDetails shopDetails = shopDetailsMapper.selectOne(Wrappers.lambdaQuery(ShopDetails.class)
                .eq(ShopDetails::getShopId, shop.getId()));

        if(ObjectUtils.isNotEmpty(shopDetails) && shopDetails.getStatus().equals("WAIT_AUDI")){
            return ApiResult.fail(500,"进件审核中，无法进行更改");
        }
        // 获取原商家用户信息
        Merchant merchant = merchantMapper.selectById(shop.getMerchantId());
        if (merchant == null) {
            return ApiResult.fail(500,"商家信息异常");
        }
        // 获取商家用户信息
        User user = userMapper.selectById(merchant.getUserId());
        if (user == null) {
            throw new BusinessException("商家账号信息异常");
        }

        // 判断联系人和手机号是否改变
        if (!platformShopParam.getContact().equals(user.getNickname()) || !platformShopParam.getMobile().equals(user.getMobile())) {
            // 如果手机号发生改变需要新手机号不能存在账号
            if (!platformShopParam.getMobile().equals(user.getMobile())) {
                User checkUser = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                        .eq(User::getMobile, platformShopParam.getMobile()));
                if (checkUser != null) {
                    throw new BusinessException("当前手机号已存在账号信息");
                }
                user.setMobile(platformShopParam.getMobile());
            }

            user.setNickname(platformShopParam.getContact());
            userMapper.updateById(user);

            // 此处清空不修改店铺本身的联系人信息，因为店铺可能是商家自己创建的
            platformShopParam.setContact(null);
            platformShopParam.setMobile(null);
        }

        BeanUtils.copyProperties(platformShopParam, shop);
        shop.setUpdateBy(LoginUtil.getUserId());
        shopMapper.updateById(shop);
        // 处理代理商绑定逻辑
        if (StringUtil.isNotBlank(platformShopParam.getAgentNo())) {
            Agent agent = agentMapper.selectOne(Wrappers.lambdaQuery(Agent.class)
                    .eq(Agent::getAgentNo, platformShopParam.getAgentNo()));
            if (agent == null) {
                throw new BusinessException("代理商信息异常");
            }

            // 获取原代绑定代理商信息
            AgentShop agentShop = agentShopMapper.selectOne(Wrappers.lambdaQuery(AgentShop.class)
                    .eq(AgentShop::getShopId, platformShopParam.getId()));
            if (agentShop == null || !Objects.equals(agentShop.getAgentId(), agent.getId())) {
                if (agentShop != null) {
                    // 将原代理商绑定信息置为不可用
                    agentShopMapper.deleteById(agentShop.getId());
                }
                AgentShop newAgentShop = new AgentShop();
                newAgentShop.setShopId(shop.getId());
                newAgentShop.setAgentId(agent.getId());
                newAgentShop.setCreateBy(LoginUtil.getUserId());
                agentShopMapper.insert(newAgentShop);
            }
        }

        // 先将原文件置为不可用重新保存即可
        shopFileMapper.delete(Wrappers.lambdaQuery(ShopFile.class)
                .eq(ShopFile::getShopId, platformShopParam.getId()));
        if (platformShopParam.getFiles() != null) {
            for (ShopFileParam shopFileParam:platformShopParam.getFiles()) {
                ShopFile shopFile = new ShopFile();
                BeanUtils.copyProperties(shopFileParam, shopFile);
                shopFile.setType(shopFileParam.getTypes());
                shopFile.setShopId(shop.getId());
                shopFileMapper.insert(shopFile);
            }
        }

        if(ObjectUtils.isEmpty(shopDetails)){
            MerchantResponse merchantResponse =  this.merchantPost(platformShopParam);

            shopDetails = new ShopDetails();
            BeanUtils.copyProperties(platformShopParam.getShopDetailsParam(), shopDetails);
            shopDetails.setShopId(String.valueOf(shop.getId()));
            shopDetails.setMerchantId(String.valueOf(merchant.getId()));
            shopDetails.setCreateBy(LoginUtil.getUserId());
            shopDetails.setCreateTime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            shopDetails.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
            shopDetails.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));

            shopDetails.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
            shopDetails.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));

            shopDetails.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
            shopDetails.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));
            shopDetails.setMerAddr(platformShopParam.getAddress());

            shopDetails.setCustomerNo(merchantResponse.getMerchantNo());
            shopDetails.setShopId(String.valueOf(shop.getId()));
            shopDetails.setCreateTime(new Date());
            shopDetails.setCreateBy( LoginUtil.getUserId());
            shopDetailsMapper.insert(shopDetails);
        }else if(!ObjectUtils.isEmpty(platformShopParam.getShopDetailsParam())){
            BeanUtils.copyProperties(platformShopParam.getShopDetailsParam(), shopDetails);

            if (shopDetails.getStatus().equals("Incoming_fail") ){
                MerchantResponse merchantResponse =  this.merchantPost(platformShopParam);
                if(ObjectUtils.isEmpty(merchantResponse)){
                    shopDetails.setStatus("Incoming_fail");
                    shopDetails.setCustomerNo("");

                }else {
                    shopDetails.setStatus("WAIT_AUDI");
                    shopDetails.setCustomerNo(merchantResponse.getMerchantNo());
                }
            }


            shopDetails.setShopId(String.valueOf(shop.getId()));
            shopDetails.setMerchantId(String.valueOf(merchant.getId()));
            shopDetails.setCreateBy(LoginUtil.getUserId());
            shopDetails.setCreateTime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            shopDetails.setLarIdCardStart(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardStart()));
            shopDetails.setLarIdCardEnd(sdf.format(platformShopParam.getShopDetailsParam().getLarIdCardEnd()));

            shopDetails.setLicenseDtStart(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtStart()));
            shopDetails.setLicenseDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getLicenseDtEnd()));

            shopDetails.setAccountIdDtStart(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtStart()));
            shopDetails.setAccountIdDtEnd(sdf.format(platformShopParam.getShopDetailsParam().getAccountIdDtEnd()));
            shopDetails.setMerAddr(platformShopParam.getAddress());

            if(!ObjectUtils.isNotEmpty(shopDetails) && shopDetails.getStatus().equals("SUCCESS")){

                //基础信息改件
                MerchantUpdateResponse merchantUpdateResponse =  this.merchantUpdate(shopDetails);
                if(ObjectUtils.isNotEmpty(merchantUpdateResponse)){
                    shopDetails.setReviewRelatedId(merchantUpdateResponse.getReviewRelatedId());
                }
                //结算信息改件
                MerchantUpdateResponse merchantUpdateSettleResponse =  this.merchantSettleUpdate(platformShopParam,shopDetails.getExternalCustomerNo());
                if(ObjectUtils.isNotEmpty(merchantUpdateResponse)){
                    shopDetails.setReviewRelatedSettleId(merchantUpdateSettleResponse.getReviewRelatedId());
                }

                //费率改件
                MerchantUpdateResponse merchantUpdateFeeResponse =  this.merchantFeeUpdate(platformShopParam,shopDetails.getExternalCustomerNo());
                if(ObjectUtils.isNotEmpty(merchantUpdateResponse)){
                    shopDetails.setReviewRelatedFeeId(merchantUpdateFeeResponse.getReviewRelatedId());
                }

            }




            shopDetails.setUpdateTime(new Date());
            shopDetails.setUpdateBy( LoginUtil.getUserId());
            shopDetailsMapper.updateById(shopDetails);

        }


        //保存业务拓展信息
        //
        ShopExpand shopExpand = new ShopExpand();
        BeanUtils.copyProperties(platformShopParam.getShopDetailsParam().getShopExpandParam(), shopExpand);
        if(ObjectUtils.isEmpty(shopExpand.getId())){
            shopExpand.setShopId(shop.getId());
            shopExpand.setCreateBy(LoginUtil.getUserId());
            shopExpand.setCreateTime(new Date());
            shopExpandMapper.insert(shopExpand);
        }else if(ObjectUtils.isNotEmpty(shopExpand.getId())){
            shopExpand.setUpdateBy(LoginUtil.getUserId());
            shopExpand.setUpdateTime(new Date());
            shopExpandMapper.updateById(shopExpand);
        }


        //保存业务拓展费率信息
        List<ShopExpandFeeParam> shopExpandFeeParams = platformShopParam.getShopDetailsParam().getShopExpandParam().getShopExpandFeeParamList();
        //先删除所有的业务拓展费率
        shopExpandFeeMapper.delete(Wrappers.lambdaQuery(ShopExpandFee.class)
                .eq(ShopExpandFee::getShopDetailsId, shopDetails.getId()));

        for (ShopExpandFeeParam shopExpandFeeParam : shopExpandFeeParams){
            ShopExpandFee shopExpandFee = new ShopExpandFee();
            BeanUtils.copyProperties(shopExpandFeeParam, shopExpandFee);
            shopExpandFee.setShopDetailsId(shopDetails.getId());
            if(ObjectUtils.isEmpty(shopExpandFee.getId())){
                shopExpandFee.setCreateBy(LoginUtil.getUserId());
                shopExpandFee.setCreateTime(new Date());
            }else {
                shopExpandFee.setUpdateBy(LoginUtil.getUserId());
                shopExpandFee.setUpdateTime(new Date());
            }
            shopExpandFeeMapper.insert(shopExpandFee);
        }



        return ApiResult.ok("请求成功");
    }

    @Override
    public boolean deleteShop(Long id) throws Exception {
        // 先获取店铺信息
        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            throw new BusinessException("店铺信息异常");
        }
        shopMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean batchDel(List<Long> ids) throws Exception {
        shopMapper.deleteBatchIds(ids);
        return true;
    }

    @Override
    public PlatformShopVo getShop(Long id) throws Exception {
        PlatformShopVo platformShopVo = shopMapper.getPlatformShopVo(id);
        // 获取文件信息
        List<ShopFileVo> files = shopFileMapper.getShopFileList(id, null);
        platformShopVo.setFiles(files);

        ShopDetails shopDetails = shopDetailsMapper.selectOne(Wrappers.lambdaQuery(ShopDetails.class)
                .eq(ShopDetails::getShopId, id));


        if(ObjectUtils.isNotEmpty(shopDetails)){
            ShopDetailsVo shopDetailsVo = new ShopDetailsVo();
            BeanUtils.copyProperties(shopDetails, shopDetailsVo);
            shopDetailsVo.setDetailsId(shopDetails.getId());
            ShopExpand shopExpand = shopExpandMapper.selectOne(Wrappers.lambdaQuery(ShopExpand.class)
                    .eq(ShopExpand::getShopId, id));
            if (ObjectUtils.isNotEmpty(shopExpand)){
                ShopExpandVo shopExpandVo = new ShopExpandVo();
                BeanUtils.copyProperties(shopExpand, shopExpandVo);
                shopExpandVo.setExpandId(shopExpand.getId());
                List<ShopExpandFee> shopExpandFeeList = shopExpandFeeMapper.selectList(Wrappers.lambdaQuery(ShopExpandFee.class)
                        .eq(ShopExpandFee::getShopDetailsId, shopDetails.getId())
                        .eq(ShopExpandFee::getDelFlag, 0)
                );
                if (ObjectUtils.isNotEmpty(shopExpandFeeList)){
                    List<ShopExpandFeeVo> shopExpandFeeVoList = new ArrayList<>();
                    for (ShopExpandFee shopExpandFee:shopExpandFeeList) {
                        ShopExpandFeeVo shopExpandFeeVo = new ShopExpandFeeVo();
                        BeanUtils.copyProperties(shopExpandFee, shopExpandFeeVo);
                        shopExpandFeeVoList.add(shopExpandFeeVo);
                    }
                    shopExpandVo.setShopExpandFeeParamList(shopExpandFeeVoList);
                }

                shopDetailsVo.setShopExpandParam(shopExpandVo);

            }


            platformShopVo.setShopDetailsParam(shopDetailsVo);
        }

        return platformShopVo;
    }

    @Override
    public Paging<PlatformShopVo> getShopPageList(PlatformShopPageParam platformShopPageParam) throws Exception {
        Page<PlatformShopVo> page = new PageInfo<>(platformShopPageParam);
        IPage<PlatformShopVo> iPage = shopMapper.getPlatformShopList(page, platformShopPageParam);
        for (PlatformShopVo platformShopVo:iPage.getRecords()) {
            //获取进件状态
            ShopDetails shopDetails = shopDetailsMapper.selectOne(Wrappers.lambdaQuery(ShopDetails.class)
                    .eq(ShopDetails::getShopId, platformShopVo.getId()));
            if(ObjectUtils.isNotEmpty(shopDetails)){
                platformShopVo.setStatus(shopDetails.getStatus());
                platformShopVo.setRemark(shopDetails.getRemark());
            }else {
                platformShopVo.setStatus("Incoming_Not");
            }

            //获取分账申请
            ShopSplit  shopSplit = shopSplitMapper.selectOne(Wrappers.lambdaQuery(ShopSplit.class)
                    .eq(ShopSplit::getShopId, platformShopVo.getId()));
            if(ObjectUtils.isNotEmpty(shopSplit)){
                platformShopVo.setShopSplitStatus(shopSplit.getAuditStatus());
                platformShopVo.setRemarkBind(shopSplit.getRemarkBind());

            }else {
                platformShopVo.setShopSplitStatus(-1);
            }

            // 获取文件信息，前端要求
            // 获取文件信息
            List<ShopFileVo> files = shopFileMapper.getShopFileList(platformShopVo.getId(), null);
            platformShopVo.setFiles(files);
        }
        return new Paging<PlatformShopVo>(iPage);
    }

    @Override
    public void updateLklShop(MerchantAudit param) throws Exception {
        ShopDetails shopDetails = shopDetailsMapper.selectOne(Wrappers.lambdaQuery(ShopDetails.class)
                .isNotNull(ShopDetails::getCustomerNo)
                .eq(ShopDetails::getCustomerNo, param.getCustomerNo()).last("limit 1"));
        if (ObjectUtils.isNotEmpty(shopDetails)){
            //商户号不一定会传过来，为空时需要反查一下商户号
            if(StringUtil.isEmpty(param.getExternalCustomerNo())){

                Map<String,Object> merchantInfo = incomingApi.getMerchantInfo(param.getCustomerNo());
                if(ObjectUtils.isNotEmpty(merchantInfo) && merchantInfo.containsKey("customer")){
                    Map<String,Object> customer = (Map<String,Object>) merchantInfo.get("customer");
                    if(ObjectUtils.isNotEmpty(customer)){
                        param.setExternalCustomerNo((String) customer.get("externalCustomerNo"));
                    }
                }

            }

            shopDetails.setExternalCustomerNo(param.getExternalCustomerNo());
            shopDetails.setAgencyNo(param.getAgencyNo());
            shopDetails.setOrgCode(param.getOrgCode());

            shopDetails.setStatus(param.getStatus());
            shopDetails.setRemark(param.getRemark());
            shopDetails.setTermNo(param.getTermNos());
            shopDetails.setUpdateTime(new Date());
            shopDetailsMapper.updateById(shopDetails);
        }

    }


    @Override
    public void updateLklShopUp(MerchantModification param) throws Exception{
        ShopDetails shopDetails = shopDetailsMapper.selectOne(new LambdaQueryWrapper<ShopDetails>()
                .eq(ShopDetails::getReviewRelatedId, param.getReviewRelatedId())
                .or().eq(ShopDetails::getReviewRelatedSettleId, param.getReviewRelatedId())
                .or().eq(ShopDetails::getReviewRelatedFeeId, param.getReviewRelatedId())
                .last("limit 1"));
        if (ObjectUtils.isNotEmpty(shopDetails) && param.getReviewRelatedId().equals(shopDetails.getReviewRelatedId())){
            shopDetails.setReviewRelatedPass(param.getReviewPass());
            shopDetails.setReviewRelatedResult(param.getReviewResult());
            shopDetails.setUpdateTime(new Date());
            shopDetailsMapper.updateById(shopDetails);
        }

        if (ObjectUtils.isNotEmpty(shopDetails) && param.getReviewRelatedId().equals(shopDetails.getReviewRelatedFeeId())){
            shopDetails.setReviewRelatedFeePass(param.getReviewPass());
            shopDetails.setReviewRelatedFeeResult(param.getReviewResult());
            shopDetails.setUpdateTime(new Date());
            shopDetailsMapper.updateById(shopDetails);
        }

        if (ObjectUtils.isNotEmpty(shopDetails) && param.getReviewRelatedId().equals(shopDetails.getReviewRelatedSettleId())){
            shopDetails.setReviewRelatedSettlePass(param.getReviewPass());
            shopDetails.setReviewRelatedSettleResult(param.getReviewResult());
            shopDetails.setUpdateTime(new Date());
            shopDetailsMapper.updateById(shopDetails);
        }
    }

    @Override
    public ApiResult<String> applyBind(String shopId) throws IOException, SDKException {

        ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getShopId, shopId));

        if(ObjectUtils.isEmpty(shopSplit)){
            return ApiResult.fail(500,"店铺未申请分账");
        }
        if(shopSplit.getAuditBindStatus().equals(1)){
            return ApiResult.fail(500,"店铺已绑定分账接收方");
        }
        if(StringUtil.isNotBlank(shopSplit.getApplyBindId()) && shopSplit.getAuditBindStatus().equals(0)){
            return ApiResult.fail(500,"店铺发送绑定申请，待审核");
        }

        //申请成功后自动绑定分账接收方
        SysInfo  sysInfo = sysInfoMapper.selectOne(new LambdaQueryWrapper<SysInfo>().last("limit 1"));

        if(ObjectUtils.isNotEmpty(sysInfo) && StringUtil.isEmpty(sysInfo.getReceiverNo())){
            //系统接收方编号为空时去创建拉卡拉接收方
            LklApplyLedgerReceiverResponse lklApplyLedgerReceiverResponse = v2SeparateAccounts.applyLedgerReceiver(StringUtil.randomDateNumOr8(), sysInfo);
            sysInfo.setReceiverNo(lklApplyLedgerReceiverResponse.getReceiverNo());
            sysInfoMapper.updateById(sysInfo);
        }
        ShopDetails  shopDetails = shopDetailsMapper.selectOne(new LambdaQueryWrapper<ShopDetails>().eq(ShopDetails::getShopId, shopSplit.getShopId()));
        //绑定分账接收方
        //上传合作协议
        String orderNo = StringUtil.randomDateNumOr8();
        String filePathBase64 = StringUtil.convertImageUrlToBase64(shopSplit.getEntrustFilePath());
        LklFileResponse lklFileResponse = v2SeparateAccounts.fileUpload(orderNo,  "SPLIT_COOPERATION_FILE", shopSplit.getEntrustFileName(), filePathBase64);

        LklApplyLedgerMerResponse response = v2SeparateAccounts.applyBind(StringUtil.randomDateNumOr8(), shopDetails, sysInfo, shopSplit.getEntrustFileName(), lklFileResponse.getAttFileId());
        if (ObjectUtils.isNotEmpty( response)){
            shopSplit.setAuditBindStatus(0);
            shopSplit.setApplyBindId(String.valueOf(response.getApplyId()));
            shopSplit.setUpdateTime(new Date());
            shopSplitMapper.updateById(shopSplit);
        }

        return ApiResult.ok("请求成功");
    }

    @Override
    public ApiResult<String> applyForSepAcc(ApplyForSepAccReq req) throws SDKException, IOException {
        Shop shop = shopMapper.selectById(req.getShopId());
        if (ObjectUtils.isEmpty(shop)){
            return ApiResult.fail("店铺信息错误，无法申请");
        }
        ShopDetails shopDetails = shopDetailsMapper.selectOne( new LambdaQueryWrapper<ShopDetails>().eq(ShopDetails::getShopId, req.getShopId()));
        if (ObjectUtils.isEmpty(shopDetails)){
            return ApiResult.fail("店铺信息错误，无法申请");
        }

        req.setCommissionRate(shop.getCommissionRate());
        ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getShopId, req.getShopId()));

        if(ObjectUtils.isNotEmpty(shopSplit) && shopSplit.getAuditStatus().equals(1)){
            return ApiResult.fail(500,"店铺已申请分账成功");
        }
        if(ObjectUtils.isNotEmpty(shopSplit) && shopSplit.getAuditStatus().equals(0)){
            return ApiResult.fail(500,"店铺申请分账审核中");
        }

        if(ObjectUtils.isNotEmpty(shopDetails) && shopDetails.getStatus().equals("WAIT_AUDI")){
            shopSplit = new ShopSplit();
            shopSplit.setShopId(Long.valueOf(req.getShopId()));
            BeanUtils.copyProperties(req, shopSplit);
            shopSplit.setCreateTime(new Date());
            shopSplit.setCreateBy(LoginUtil.getUserId());
            shopSplitMapper.insert(shopSplit);
            return ApiResult.fail(500,"未进件成功，无法申请分账");
        }

        req.setCustomerNo(shopDetails.getCustomerNo());
        String orderNo = StringUtil.randomDateNumOr8();
        String filePathBase64 = StringUtil.convertImageUrlToBase64(req.getSplitEntrustFilePath());
        LklFileResponse lklFileResponse = v2SeparateAccounts.fileUpload(orderNo,  "SPLIT_ENTRUST_FILE", req.getSplitEntrustFileName(), filePathBase64);
        if (ObjectUtils.isEmpty(lklFileResponse)){
            return ApiResult.fail("申请失败,文件上传失败");
        }
        ApplyForSepAccReq reqInfo = new ApplyForSepAccReq();
        BeanUtils.copyProperties(req, reqInfo);
        reqInfo.setSplitEntrustFilePath(lklFileResponse.getAttFileId());
        reqInfo.setExternalCustomerNo(shopDetails.getExternalCustomerNo());
        LklApplyLedgerMerResponse lklApplyLedgerMerResponse = v2SeparateAccounts.applyLedgerMer(orderNo,reqInfo);
        if (ObjectUtils.isEmpty(lklApplyLedgerMerResponse)){
            return ApiResult.ok("申请失败");
        }


        if (ObjectUtils.isEmpty(shopSplit)){
            shopSplit = new ShopSplit();
            shopSplit.setShopId(Long.valueOf(req.getShopId()));
            BeanUtils.copyProperties(req, shopSplit);
            shopSplit.setCreateTime(new Date());
            shopSplit.setCreateBy(LoginUtil.getUserId());
            shopSplit.setApplyId(String.valueOf(lklApplyLedgerMerResponse.getApplyId()));
            shopSplitMapper.insert(shopSplit);

        }else {
            BeanUtils.copyProperties(req, shopSplit);
            shopSplit.setUpdateTime(new Date());
            shopSplit.setUpdateBy( LoginUtil.getUserId());
            shopSplit.setAuditStatus(0);
            shopSplit.setApplyId(String.valueOf(lklApplyLedgerMerResponse.getApplyId()));
            shopSplitMapper.updateById(shopSplit);

        }
        return ApiResult.ok("请求成功");

    }

    @Override
    public ApiResult<ShopSplitVo> getApplyForSepAcc(String shopId) {

        ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getShopId, shopId));

        ShopSplitVo shopSplitVo = new ShopSplitVo();
        if(ObjectUtils.isNotEmpty(shopSplit)){
            BeanUtils.copyProperties(shopSplit, shopSplitVo);
        }
        return ApiResult.ok(shopSplitVo);
    }



    @Override
    public Map<String, Object> applyLedgerMerNot(String body) throws SDKException, IOException {
        Map<String, Object> result = new HashMap<>();

        try {
            JSONObject jsonObject = JSONUtil.parseObj(body);
            ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getApplyId, jsonObject.get("applyId").toString()));
            if (ObjectUtils.isEmpty(shopSplit)){
                result.put("code", "FAIL");
                result.put("message", "申请记录不存在");
                return result;
            }
            shopSplit.setAuditStatus(Integer.parseInt( jsonObject.get("auditStatus").toString()));
            shopSplit.setUpdateTime(new Date());
            if(jsonObject.containsKey("remark")){
                shopSplit.setRemark(jsonObject.get("remark").toString());
            }
            shopSplitMapper.updateById(shopSplit);
            if(jsonObject.get("auditStatus").equals(1)){
                //申请成功后自动绑定分账接收方
                SysInfo  sysInfo = sysInfoMapper.selectOne(new LambdaQueryWrapper<SysInfo>().last("limit 1"));
                if(ObjectUtils.isNotEmpty(sysInfo) && StringUtil.isEmpty(sysInfo.getReceiverNo())){
                    //系统接收方编号为空时去创建拉卡拉接收方
                    LklApplyLedgerReceiverResponse lklApplyLedgerReceiverResponse = v2SeparateAccounts.applyLedgerReceiver(StringUtil.randomDateNumOr8(), sysInfo);
                    sysInfo.setReceiverNo(lklApplyLedgerReceiverResponse.getReceiverNo());
                    sysInfoMapper.updateById(sysInfo);
                }
                ShopDetails  shopDetails = shopDetailsMapper.selectOne(new LambdaQueryWrapper<ShopDetails>().eq(ShopDetails::getShopId, shopSplit.getShopId()));
                //绑定分账接收方
                //上传合作协议
                String orderNo = StringUtil.randomDateNumOr8();
                String filePathBase64 = StringUtil.convertImageUrlToBase64(shopSplit.getEntrustFilePath());
                LklFileResponse lklFileResponse = v2SeparateAccounts.fileUpload(orderNo,  "SPLIT_COOPERATION_FILE", shopSplit.getEntrustFileName(), filePathBase64);

                LklApplyLedgerMerResponse response = v2SeparateAccounts.applyBind(StringUtil.randomDateNumOr8(), shopDetails, sysInfo, shopSplit.getEntrustFileName(), lklFileResponse.getAttFileId());
                if (ObjectUtils.isNotEmpty( response)){
                    shopSplit.setAuditBindStatus(0);
                    shopSplit.setApplyBindId(String.valueOf(response.getApplyId()));
                    shopSplit.setUpdateTime(new Date());
                    shopSplitMapper.updateById(shopSplit);
                }
            }

            result.put("code", "SUCCESS");
            result.put("message", "请求成功");
            return result;
        } catch (Exception e) {
            log.error("请求失败", e);
            result.put("code", "FAIL");
            result.put("message", e.getMessage());
            return result;
        }
    }


    @Override
    public Map<String, Object> applyLedgerMerUpdateNot(String body) throws SDKException, IOException {
        Map<String, Object> result = new HashMap<>();

        try {
            JSONObject jsonObject = JSONUtil.parseObj(body);
            ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getApplyUpdateId, jsonObject.get("applyId")));
            if (ObjectUtils.isEmpty(shopSplit)){
                result.put("code", "FAIL");
                result.put("message", "申请记录不存在");
                return result;
            }
            shopSplit.setAuditStatus((Integer) jsonObject.get("auditStatus"));
            shopSplit.setUpdateTime(new Date());
            shopSplitMapper.updateById(shopSplit);

            result.put("code", "SUCCESS");
            result.put("message", "请求成功");
            return result;
        } catch (Exception e) {
            log.error("请求失败", e);
            result.put("code", "FAIL");
            result.put("message", e.getMessage());
            return result;
        }
    }


    @Override
    public Map<String, Object> applyBindNot(String body){
        Map<String, Object> result = new HashMap<>();

        try {
            JSONObject jsonObject = JSONUtil.parseObj(body);
            ShopSplit shopSplit = shopSplitMapper.selectOne(new LambdaQueryWrapper<ShopSplit>().eq(ShopSplit::getApplyBindId, jsonObject.get("applyId")));
            if (ObjectUtils.isEmpty(shopSplit)){
                result.put("code", "FAIL");
                result.put("message", "申请记录不存在");
                return result;
            }
            shopSplit.setAuditBindStatus((Integer) jsonObject.get("auditStatus"));
            shopSplit.setRemarkBind((String) jsonObject.get("remark"));

            shopSplit.setUpdateTime(new Date());
            shopSplitMapper.updateById(shopSplit);

            result.put("code", "SUCCESS");
            result.put("message", "请求成功");
            return result;
        } catch (Exception e) {
            log.error("请求失败", e);
            result.put("code", "FAIL");
            result.put("message", e.getMessage());
            return result;
        }
    }



    public String   paramCheck(PlatformShopParam platformShopParam){
        if (platformShopParam == null){
            return "参数错误";
        }

        ShopDetailsParam request = platformShopParam.getShopDetailsParam();
        if (ObjectUtils.isEmpty(platformShopParam.getLatitude())){
            return "经度不能为空";
        }
        if (ObjectUtils.isEmpty(platformShopParam.getLongitude())){
            return "纬度不能为空";
        }
        if (StringUtil.isEmpty(platformShopParam.getShopName())){
            return "店铺名称不能为空";
        }
        if (ObjectUtils.isEmpty(platformShopParam.getContact())){
            return "店铺联系人不能为空";
        }
        if (ObjectUtils.isEmpty(platformShopParam.getMobile())){
            return "店铺联系电话不能为空";
        }
        if (StringUtil.isEmpty(platformShopParam.getAddress())){
            return "详细地址不能为空";
        }

        if (StringUtil.isEmpty(platformShopParam.getCityCode()) || StringUtil.isEmpty(platformShopParam.getProvCode()) || StringUtil.isEmpty(platformShopParam.getDistCode())){
            return "地址编码不能为空";
        }

        if (request == null){
            return "参数错误";
        }

        if (StringUtil.isEmpty(request.getEmail())){
            return "商户邮箱不能为空";
        }
        if (StringUtil.isEmpty(request.getMerRegName())){
            return "商户注册名称不能为空";
        }
        if (StringUtil.isEmpty(request.getMerType())){
            return "商户类型不能为空";
        }
        if (StringUtil.isEmpty(request.getMerName())){
            return "商户名称(经营名称)不能为空";
        }


        if(!StringUtil.equals("TP_PERSONAL",request.getMerType())){
            if (StringUtil.isEmpty(request.getLicenseNo())){
                return "商户营业执照编号不能为空";
            }
            if (StringUtil.isEmpty(request.getLicenseDtStart())){
                return "商户营业执照开始日期不能为空";
            }
            if (StringUtil.isEmpty(request.getLicenseDtEnd())){
                return "商户营业执照结束日期不能为空";
            }
        }

        if (StringUtil.isEmpty(request.getSource())){
            request.setSource("H5");
//            return "商户来源不能为空";
        }
        if (StringUtil.isEmpty(request.getBusinessContent())){
            return "商户经营内容不能为空";
        }


        if (StringUtil.isEmpty(request.getLarName())){
            return "商户法人姓名不能为空";
        }
        if (StringUtil.isEmpty(request.getLarIdType())){
            return "商户法人证件类型不能为空";
        }
        if (StringUtil.isEmpty(request.getLarIdCard())){
            return "商户法人证件号码不能为空";
        }
        if (StringUtil.isEmpty(request.getLarIdCardStart())){
            return "商户法人证件开始日期不能为空";
        }
        if (StringUtil.isEmpty(request.getLarIdCardEnd())){
            return "商户法人证件结束日期不能为空";
        }
        //  if (StringUtil.isEmpty(request.getContactMobile())){
        //     return "商户联系⼈⼿机号码不能为空";
        //  }
       // if (StringUtil.isEmpty(request.getContactName())){
        //   return "商户联系⼈姓名不能为空";
        //  }
        if (StringUtil.isEmpty(request.getOpenningBankCode())){
            return "结算账户开户行号不能为空";
        }
        if (StringUtil.isEmpty(request.getOpenningBankName())){
            return "结算账户开户行名称不能为空";
        }
        if (StringUtil.isEmpty(request.getClearingBankCode())){
            return "结算账户清算⾏号不能为空";
        }
        if (StringUtil.isEmpty(request.getSettleProvinceCode())){
            return "结算信息省份名称不能为空";
        }
        if (StringUtil.isEmpty(request.getSettleProvinceName())){
            return "结算信息城市代码不能为空";
        }
        if (StringUtil.isEmpty(request.getSettleCityCode())){
            return "结算信息城市代码不能为空";
        }
        if (StringUtil.isEmpty(request.getSettleCityName())){
            return "结算信息城市名称不能为空";
        }


        if (StringUtil.isEmpty(request.getAccountNo())){
            return "结算人银行卡号不能为空";
        }
        if (StringUtil.isEmpty(request.getAccountName())){
            return "结算账户名称不能为空";
        }
        if (StringUtil.isEmpty(request.getAccountType())){
            return " 结算账户类型 不能为空";
        }

        if (StringUtil.isEmpty(request.getAccountIdCard())){
            return "结算⼈证件号码不能为空";
        }
        if (StringUtil.isEmpty(request.getSettleType())){
            return "结算类型不能为空";
        }

        if (ObjectUtils.isEmpty(request.getAccountIdDtStart())){
            return "结算人证件开始时间不能为空";
        }

        if (ObjectUtils.isEmpty(request.getAccountIdDtEnd())){
            return "结算人证件结束时间不能为空";
        }

        if (ObjectUtils.isEmpty(request.getSettlementType())){
            return "结算方式不能为空";
        }
        if(request.getSettlementType().equals("REGULAR") && ObjectUtils.isEmpty(request.getRegularSettlementTime())){
            return "结算时间不能为空";
        }
        if(ObjectUtils.isEmpty(request.getShopExpandParam())){
            return "商户业务扩展信息不能为空";
        }
        if(ObjectUtils.isEmpty(request.getShopExpandParam().getMcc())){
            return "商户业务扩展信息的商户mcc编号不能为空";
        }
        if(ObjectUtils.isEmpty(request.getShopExpandParam().getTermNum())){
            return "商户业务扩展信息的终端数量不能为空";
        }
        if(ObjectUtils.isEmpty(request.getShopExpandParam().getWithdrawalType())){
            return "商户业务扩展信息的提款类型不能为空";
        }

        if(ObjectUtils.isEmpty(request.getShopExpandParam().getShopExpandFeeParamList())){
            return "商户业务扩展信息的费率列表不能为空";
        }
        return null;
    }

}
